
package net.vinote.smart.platform.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpSession;

import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.DataWindowCatalog;
import net.vinote.smart.platform.service.bean.User;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class FileUploadController
{
	@RequestMapping(value = "fileUpload.html", method = RequestMethod.POST, produces = "application/json")
	public String handleFormUpload(@RequestParam("name")
	String name, @RequestParam("doNo")
	String doNo, @RequestParam("model")
	String model, @RequestParam("file")
	MultipartFile file, HttpSession session)
	{

		if (!file.isEmpty())
		{
			User user = (User) session.getAttribute("user");
			String savePath = session.getServletContext().getRealPath("/")
					+ File.separator + "WEB-INF" + File.separator + "attache"
					+ File.separator + user.getUserID() + File.separator
					+ model;
			// 对同一用户的图片资源进行按表引用分类
			DataWindowCatalog catalog = SRE.getDataWindowCatalog(doNo);
			if (catalog != null)
			{
				savePath += File.separator
						+ catalog.getMainTable().toLowerCase();
			}

			// 创建文件存储目录
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists())
			{
				saveDirFile.mkdirs();
			}

			String fileType = file.getContentType();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000);
			if (fileType != null)
			{
				newFileName += "." + fileType;
			}
			File uploadedFile = new File(savePath, newFileName);
			try
			{
				file.transferTo(uploadedFile);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return "redirect:uploadSuccess";
		}

		return "redirect:uploadFailure";
	}

	@RequestMapping(value = "upload.html")
	public String showPage()
	{
		System.out.println("hahaha");
		return "upload";
	}
}
